package com.lala.rennigou.Util;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import java.io.*;

public class FTPUtil {
    //ip地址
    private static final String FTP_ADDRESS = "39.104.78.30";
    //端口号
    private static final int FTP_PORT = 21;

    //ftp用户名
    private static final String FTP_USERNAME = "ahhua";
    //ftp密码
    private static final String FTP_PASSWORD = "123456";

    private static final String FTP_BASEPATH = "/home/ahhua/files/";

    //文件上传                                   //文件名       io输入流
    public static boolean uploadFile(String fileName, InputStream input) {
        boolean success = false;
        //new有个客户端
        FTPClient ftp = new FTPClient();
        try {
            int reply;


            ftp.connect(FTP_ADDRESS, FTP_PORT);

            ftp.login(FTP_USERNAME, FTP_PASSWORD);
            reply = ftp.getReplyCode();

            //如果没有连上，那么就自动断开
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return false;
            }
            ftp.setControlEncoding("UTF-8");
            //设置文件类型                二进制
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
            //创建文件夹
            // ftp.makeDirectory(FTP_BASEPATH);
            //改变目录
            ftp.changeWorkingDirectory(FTP_BASEPATH);
            ftp.enterLocalActiveMode();

            //传文件
            ftp.storeFile(fileName, input);
            //输入流关闭
            input.close();
            //ftp注销
            ftp.logout();
            success = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return success;
    }
}
